<template>
  <div class="invoice-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>发票管理</span>
        </div>
      </template>
      
      <el-table
        :data="invoices"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="发票ID" prop="invoiceId" width="100" />
        <el-table-column label="客户ID" prop="clientId" />
        <el-table-column label="发票金额" prop="totalAmount" />
        <el-table-column label="发票日期">
          <template #default="scope">
            {{ formatDate(scope.row.invoiceDate) }}
          </template>
        </el-table-column>
        <el-table-column label="开票状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button 
              type="success" 
              link 
              v-if="scope.row.status === '未开票'"
              @click="handleIssue(scope.row)"
            >开具发票</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'InvoiceList',
  setup() {
    const store = useStore()
    const router = useRouter()
    const invoices = ref([])
    const loading = ref(false)
    
    const fetchInvoices = async () => {
      loading.value = true
      try {
        const data = await store.dispatch('fetchInvoices')
        console.log('获取到的发票数据:', data)
        if (data && data.length > 0) {
          console.log('第一条发票数据:', data[0])
          console.log('发票ID字段:', data[0].invoiceId)
        }
        invoices.value = data
      } catch (error) {
        console.error('获取发票列表失败:', error)
        ElMessage.error('获取发票列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit'
      })
    }
    
    const getStatusType = (status) => {
      switch(status) {
        case '已开票':
          return 'success'
        case '未开票':
          return 'warning'
        case '已取消':
          return 'danger'
        default:
          return 'info'
      }
    }
    
    const getStatusText = (status) => {
      if (!status) return '未知'
      return status
    }
    
    const handleView = (invoice) => {
      console.log('查看发票详情:', invoice)
      router.push(`/invoices/${invoice.invoiceId}`)
    }
    
    const handleIssue = (invoice) => {
      ElMessageBox.confirm(
        `确认开具发票: ID ${invoice.invoiceId}，金额 ${invoice.totalAmount}元?`,
        '开票确认',
        {
          confirmButtonText: '确认开票',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await axios.put(`invoices/${invoice.invoiceId}/issue`)
          if (response.data.code === 200) {
            ElMessage.success('开票成功')
            fetchInvoices()
          } else {
            ElMessage.error(response.data.message || '开票失败')
          }
        } catch (error) {
          console.error('开票失败:', error)
          ElMessage.error('开票失败: ' + error.message)
        }
      }).catch(() => {
        ElMessage.info('已取消开票')
      })
    }
    
    onMounted(() => {
      fetchInvoices()
    })
    
    return {
      invoices,
      loading,
      handleView,
      handleIssue,
      formatDate,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.invoice-list {
  padding: 20px;
}

.list-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>